package controller;

import implementor.BalancePaymentDaoImplementor;
import implementor.BillImplementor;
import implementor.CustomerImp;
import implementor.MaterialImp;
import implementor.SellImp;
import implementor.TransactionDaoImplementor;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Vector;

import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.table.DefaultTableModel;

import daoInterface.BalancePaymentDao;
import daoInterface.BillDao;
import daoInterface.CustomerDao;
import daoInterface.MaterialDao;
import daoInterface.SellDao;
import daoInterface.TransactionDao;
import dbhandeling.Connections;
import dto.BalancePayment;
import dto.Customer;
import dto.Sell;
import dto.Transactions;

import uiframework.Validater;
import utilities.AppUtilites;
import utilities.ViewUtilites;
import views.bill.Bill;

public class BillController implements ActionListener,CaretListener{
	private Bill view;
	private Sell si;
	private Vector<Sell>vec;
	private static double  total=0;
	private static int srno =1;
	int transCatId; //comments
	
	public BillController() {
		
	}

	public BillController(Bill view, Sell si) {
		super();
		this.view = view;
		this.si = si;
		view.actionListeners(this);
		view.getTfDiscount().addCaretListener(this);
		view.getTfPaidAmount().addCaretListener(this);
		
		total=0;
		srno=0;
		vec= new Vector<Sell>();
		this.setBill();
		AppUtilites.getTime(view.getTfTime());
	}

	public Bill getView() {
		return view;
	}

	public void setView(Bill view) {
		this.view = view;
	}

	public Sell getModel() {
		return si;
	}

	public void setModel(Sell si) {
		this.si = si;
	}
	
	public void reactOnAdd()
	{
		    fillmodelfromview();
			vec.add(si);
			double total=si.getSellMrp()*si.getSellQuant();
			double amt=((total*10)/100)+total;
			DefaultTableModel dm= (DefaultTableModel) view.getTable().getModel();
			dm.addRow(new Object[]{srno++,si.getmCode(),si.getModelMaterial().getCategoryname(),si.getModelMaterial().getmMrp(),si.getDiscount(),si.getSellMrp(),si.getSellQuant(),
				10,amt});
			updateTotal();
	}
	
	public void reactOnSave() throws Exception 
	{
		//save in customer
		Connection con = Connections.getMyConnection();
		 con.setAutoCommit(false);
		 try
		 {
			 int customerid=saveInCustomer();
			 System.out.println("id customer "+customerid);
			 int balancepayid=saveInBalancePayment();
			 System.out.println("id balance "+balancepayid);
			 int key=saveInBill(customerid, balancepayid);
			 saveInSell(key);
			 System.out.println("bill id "+key);
			 saveInTransaction(balancepayid);
		 }
		 catch(SQLException e)
		 {
			 e.printStackTrace();
			 con.rollback();
		 }
		con.setAutoCommit(true);
		
	}
	
	public  int saveInBalancePayment()
	{
		 double totalamt=Double.parseDouble(view.getTfTotal().getText().trim());
		 double paidamour=  Double.parseDouble(view.getTfPaidAmount().getText().trim());
		 String temp = view.getTfBillDate().getText();
		 java.sql.Date date =ViewUtilites.convert(temp);
		 
		 BalancePayment bal=new BalancePayment(0, totalamt, paidamour, date, 1);
		 BalancePaymentDao bimp=new BalancePaymentDaoImplementor();
		 try {
			bimp.add(bal);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 int balancePaymentId=bimp.getAutoGenratedKey();
		return balancePaymentId;
	}
	
	public void saveInTransaction(int balancePaymentId)
	{
		String temp = view.getTfBillDate().getText();
		 java.sql.Date date =ViewUtilites.convert(temp);
		 double paidamour=  Double.parseDouble(view.getTfPaidAmount().getText().trim());
		 int billno=Integer.parseInt((view.getTfBillNo().getText().trim()));
		 
		Transactions transaction=new Transactions(0,1 ,paidamour, date, 1, billno+"",balancePaymentId);
		 TransactionDao timp=new TransactionDaoImplementor();
		 try {
			timp.add(transaction);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	
	private void fillmodelfromview()
	{
		si=new Sell();		
		si.setmCode(view.getTfMcode().getText().trim());
		si.setMaterial();
		//System.out.println(si.getModelMaterial().getCatId()+"  "+si.getModelMaterial().getmCode()+"  "+si.getModelMaterial().getmMrp());
		String taxcode=null;
	    si.setDiscount(Double.parseDouble(view.getTfDiscount().getText()));
		si.setSellQuant(Integer.parseInt(view.getTfQty().getText()));
		si.setTaxCode(taxcode);
		double sellprice=Double.parseDouble(view.getTfSellPrice().getText().trim());
		si.setSellMrp(sellprice);
	}
	
	private int saveInCustomer() throws Exception
	{
		CustomerDao custd=new CustomerImp();
		int key = 0;
		// Get Customer from view
		String custname=view.getTfCustName().getText().trim();
		double custph=Double.parseDouble(view.getTfCustPhone().getText().trim());
		//Check weather it exist prviously
		Customer prev=null;
		try{
		prev= custd.retrieve("customerPhone",custph+"");
		key=prev.getAutocustomerId();
		
		}
		catch(Exception e)
		{
			prev=null;
			e.printStackTrace();
		}
		if(prev==null)
		{
		 Customer cust=new Customer( custname, custph);
		 custd=new CustomerImp();
	     custd.add(cust);
	     
	     key=custd.getAutoGenratedKey();
	    
		}
		
		return key;
	}
	
	private int saveInBill(int customerId,int id) throws SQLException, Exception
	{
		 String temp = view.getTfBillDate().getText();
		 java.sql.Date date =ViewUtilites.convert(temp);
		 dto.Bill bil=new dto.Bill();
		 bil.setbillDate(date);
		 bil.setcustomerId(customerId);
		 bil.setBalancePaymentId(id);
		 BillDao billimp=new BillImplementor();
		 billimp.add(bil);
		 int key=billimp.getAutoGenratedKey();
		 return key;
	}
	
	public void saveInSell(int key) throws SQLException, Exception
	{
		 
		 SellDao sellimp = new SellImp();
		
		 MaterialDao materialimp = new MaterialImp();
		 
		 for(int i =0;i<vec.size();i++)
		 {
			 double updatedMquant = vec.get(i).getModelMaterial().getmQuant()-vec.get(i).getSellQuant();
			 
			 if(updatedMquant<0)
			 {
				 JOptionPane.showMessageDialog(null,"Invalid Quantity For Mcode "+vec.get(i).getmCode());
				 continue;
			 }
			 else
			 {
				 System.out.println("Pradnya"+vec.get(i).getmCode()+" "+vec.get(i).getSellMrp()+" "+vec.get(i).getModelMaterial().getmCode());
				 vec.get(i).getModelMaterial().setmQuant(updatedMquant);
				 materialimp.update(vec.get(i).getModelMaterial());
				 vec.get(i).setBillId(key);
				 sellimp.add(vec.get(i));
				
			 }
			 
		 }
	}
	
	public void reactOnPrint()
	{
		try {
			reactOnSave();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 
	 */
	
	private void updatediscount()
	{
		double  mrp =Double.parseDouble(view.getTfMrp().getText().trim());
		double sellprice= Double.parseDouble(view.getTfSellPrice().getText().trim());
		double discount= (mrp-sellprice)*100/mrp;
		view.getTfDiscount().setText(discount+"");
		
	}
	
	private void updatesellprice()
	{
		double  mrp =Double.parseDouble(view.getTfMrp().getText().trim());
		double discount= Double.parseDouble(view.getTfDiscount().getText().trim());
		double sellprice= (mrp-(mrp*discount)/100);
		view.getTfSellPrice().setText(sellprice+"");
		
	}
	
	
	
	private void updateTotal()
	{
		double sellprice= Double.parseDouble(view.getTfSellPrice().getText().trim());
		//double tax = Double.parseDouble(view.getTax().getText().trim());
		double tax=10;
		double qty = Double.parseDouble(view.getTfQty().getText().trim());
		double amt= (qty*sellprice)+(tax*sellprice*qty)/100;
		total=total+amt;
		view.getTfTotal().setText(total+"");
	}
	
	private void updateBalance()
	{
		
		
		if(view.getTfTotal().getText().equals(""))
		{
			//JOptionPane.showMessageDialog(null, "empty total");
		}
		else
		{
		double total=Double.parseDouble(view.getTfTotal().getText().trim());
		double paidAmount=Double.parseDouble(view.getTfPaidAmount().getText().trim());
		double balance=total-paidAmount;
		view.getTfBalance().setText(balance+"");
		}
	}

	
	
	@Override
	public void actionPerformed(ActionEvent arg0) {
		String k=arg0.getActionCommand();
		
		if(k.contains("ADD"))
		{
			reactOnAdd();
		}
		
		if(k.contains("Print"))
		{
			reactOnPrint();
		}
		if(k.equals("Bill Date:"))
		{
			ViewUtilites.makeDateComponent(view.getTfBillDate());
		}
		
	}

	private void setBill()
	{
		BillDao dao=new BillImplementor();
		int key=dao.getAutoGenratedKey();
		view.getTfBillNo().setText((key+1)+"");
	}
	
	@Override
	public void caretUpdate(CaretEvent arg0) {
	
	JTextField discount=view.getTfDiscount();
	JTextField sellprice=view.getTfSellPrice();
	JTextField paidamount=view.getTfPaidAmount();
	JTextField f=(JTextField) arg0.getSource();
	if(f.getText().trim().equals("")== true)
		return ;
	if(f==discount)
	{
		updatesellprice();
	}
	if(f==sellprice)
	{
		updatediscount();
	}
	if(f==paidamount)
	{
		updateBalance();
	}
	//System.out.println(f.getText());
		
	}
	
	

}
